package com.kt.coroutinedemo.Netty

import android.util.Log
import com.streamax.app.cqbus.platform.ext.capture
import com.swallowsonny.convertextlibrary.toHexString
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelId
import io.netty.channel.SimpleChannelInboundHandler

/**
 * @Author Xzh
 * @Date 2025/6/5
 * @Description
 */
 class ClientHandler(val listener :LinkListener) : SimpleChannelInboundHandler<ByteBuf>() {

    private val TAG = "ClientHandler"

    /**
     * 与服务端连接成功的回调
     *
     * @param ctx
     * @throws Exception
     */
    @Throws(Exception::class)
    override fun channelActive(ctx: ChannelHandlerContext) {
        super.channelActive(ctx)
        Log.d(TAG, "与服务端连接成功：$ctx")
        listener.linkSuccess(ctx.channel().id())
    }

    /**
     * 与服务端断开的回调
     *
     * @param ctx
     * @throws Exception
     */
    @Throws(Exception::class)
    override fun channelInactive(ctx: ChannelHandlerContext) {
        super.channelInactive(ctx)
        Log.d(TAG, "与服务端断开连接：$ctx")
        NettyClient.channel = null
    }

    /**
     * 当收到数据的回调
     *
     * @throws Exception
     */
    @Throws(Exception::class)
    override fun messageReceived(ctx: ChannelHandlerContext, msg: ByteBuf) {
        Log.d(TAG, "messageReceived: $ctx msg:${msg})")

        NettyClient.handleResponse( msg.array())
        listener.onDataReceived(msg.array())
    }


}